<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class PriceController extends Controller
{
    //价格管理首页
    public function getIndex(Request $request)
    {

        $count = 1;
        //判断是否有查询
        if($request -> input('keywords')){
            $prices = DB::table('mprice')
                ->where('mName','like','%'.$request->input('keywords').'%')
                ->orWhere('from','like','%'.$request->input('keywords').'%')
                ->orWhere('market','like','%'.$request->input('keywords').'%')
                ->paginate(10);
        }else{
            //查询所有的价格
            $prices = DB::table('mprice') -> paginate(10);    
        }
        //获取所有的信息
        $data = $request -> all();
    	return view('Admin.price.index',['prices' => $prices,'count' => $count,'data' => $data]);
    }

    //价格添加页面
    public function getAdd()
    {
    	return view('Admin.price.add');
    }

    //执行药材添加
    public function postInsert(Request $request)
    {
        // dd($request -> all());
        $data = $request -> except(['_token']);
        $data['time'] = time();
        // dd($data);
        $data['token'] = str_random(50);
        // dd($data);
        //执行数据的插入
        $res = DB::table('mprice') -> insert($data);
        if($res){
            return redirect('/admin/price/index') -> with('success','价格添加成功');
        }else{
            return back() -> with('error','价格添加失败');
        }
    }

    //价格修改页面
    public function getEdit($id)
    {   
        // dd($id);
        //获取信息
        $res = DB::table('mprice') -> where('id',$id) -> first();
        // dd($res);

        //解析模板
    	return view('Admin.price.edit',['prices' => $res]);
    }

    //执行修改
    public function postUpdate(Request $request)
    {
        // dd($request -> all());
        $id = $request -> input('pid');
        // dd($id);
        $data = $request -> except(['_token','pid']);
        // dd($data);
        $res = DB::table('mprice') -> where('id',$id) -> update($data);
        if($res){
            return redirect('/admin/price/index') -> with('success','价格修改成功');
        }else{
            return back() -> with('error','价格修改失败');
        }
    }

    //删除操作
    public function getDelete($id)
    {
        // dd($id);
        //执行删除
        $res = DB::table('mprice') -> where('id',$id) -> delete();
        if($res){
            return redirect('/admin/price/index') -> with('success','价格删除成功');
        }else{
            return back() -> with('error','用户删除失败');
        }
    }
}
